Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

134
Visualizações
How to set first value in "useState" function to true or false with "useEffect" function React

I am running into a problem with my current code. The code below is supposed to grab a JSON response from my backend and set "data" in the useState function to true or false based on the backend's response. The issue I am having is that when I click on my button to redirect me to the page it must first go through this protected route in my react router. So it will run this script but the value of 'data' never changes. However, my console.log will output the correct boolean based on the JSON response sent from the backend. I am confused on how I can actually grab my JSON response on page load and set it to 'data' with useEffect? From my understanding, useEffect will only update my useState 'data' when the DOM re-renders.

In short, I want data to = true on page render by checking the JSON response from my backend using axios and if it is true I want to be redirected to the outlet.

I appreciate any help thanks.

 const useAuth = () => {
    
      const [data, setData] = useState(false);
    
      useEffect(() => {
        const fetchAuthData = async () => {
          await axios.get('http://localhost:5000/auth')
            .then(resp => {
              console.log(resp.data)
              setData(resp.data);
            })
            .catch(err => {
              console.log(err);
              setData(false)
            });
    
    
        };
    
        fetchAuthData()
      }, []);
    
      console.log(data)
      // Logic to check if backEndResponse is true or false
      if (data === true) {
        const authorized = { loggedIn: true }
        return authorized && authorized.loggedIn;
      } else {
        const authorized = { loggedIn: false }
        return authorized && authorized.loggedIn;
      }
    
    };
    
    
    const ProtectedRoutes = () => {
      const isAuth = useAuth();
      return isAuth ? <Outlet/> : <Navigate to="/login" />;
    }
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Ok, from what I can understand of your question, the issue is that the ProtectedRoutes layout component is using the initial data state, which is false, and handling the auth redirect before the actual auth GET request is fully processed.

You should use a third "indeterminant" state to hold off on rendering the Outlet or redirect until the auth status is confirmed.

Example:

const useAuth = () => {
  const [data, setData] = useState(); // <-- initially undefined

  useEffect(() => {
    const fetchAuthData = async () => {
      await axios.get('http://localhost:5000/auth')
        .then(resp => {
          setData(!!resp.data);
        })
        .catch(err => {
          console.log(err);
          setData(false)
        });
    };

    fetchAuthData()
  }, []);

  return data;
};

...

const ProtectedRoutes = () => {
  const isAuth = useAuth();

  if (isAuth === undefined) return null; // or loading indicator, etc...

  return isAuth ? <Outlet/> : <Navigate to="/login" replace />;
}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda